package cc.wanforme.fsync.server.task;

import cc.wanforme.fsync.entity.po.SyncLog;
import cc.wanforme.fsync.entity.ws.WsRes;
import cc.wanforme.fsync.server.LoginController;
import cc.wanforme.fsync.util.LoggerTool;
import jakarta.websocket.Session;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Vector;

/** 监听同步事件 */
@Component
public class SyncEventListener implements ApplicationListener<SyncEvent> {
    private static final Logger logger = LoggerTool.getLogger();
    private TaskWebsocketSessions sessions;

    @Override
    public void onApplicationEvent(SyncEvent event) {
        if(SyncEvent.FINISH.equals(event.getStatus())) {
            syncFinished(event.getSyncLog());
        }
    }

    /** 推送 同步完成的消息 */
    private void syncFinished(SyncLog log) {
        Long userId = LoginController.LOGIN_ID;
        Vector<Session> list = sessions.list(userId);

        if(list == null || list.isEmpty()) {
            return;
        }

        for (Session s: list) {
            try {
                TaskWebsocket.sendMessage(s, WsRes.New(WsRes.FINISH, log));
            } catch (IOException e) {
                logger.error("websocket-message fail to send", e);
            }
        }
    }

    @Autowired
    public void setSessions(TaskWebsocketSessions sessions) {
        this.sessions = sessions;
    }

}
